from django.shortcuts import render
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django import http
from django.views import View
from django.http import JsonResponse
from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generate_access_token_openid, check_access_token_openid
from django.contrib.auth import login
from apps.oauth.models import OAuthQQUser
import re, json
from django_redis import get_redis_connection
from apps.users.models import User


# Create your views here.
class OAuthURLView(View):
    def get(self, request):
        # 接受前端传的 next
        # next = request.Get.get('next','/')  错误示范，应该是    请求.GET
        next = request.GET.get('next', '/')

        # 创建OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        # qq登录扫码接口
        login_url = oauth.get_qq_url()

        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'login_url': login_url})


class OAuthUserView(View):
    def get(self, request):
        # 以查询字符串方式接受code
        code = request.GET.get('code')

        if not code:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少code'})

        # 创建oauth对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # 获取token
            access_token = oauth.get_access_token(code)

            # 把token作为参数，再次发送请求，获取openid
            openid = oauth.get_open_id(access_token)

        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': "OAuth2.0认证失败"})

        # 把openid作为条件在OAuthQQUser中检索. 获取对象
        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)


            # 11.把openid加密为access_token
        except OAuthQQUser.DoesNotExist:
            access_token = generate_access_token_openid(openid)

            # 12.把access_token返回
            return JsonResponse({'code': 300,
                                 'errmsg': "ok",
                                 'access_token': access_token})

        else:
            # openid已绑定美多商城的用户：直接实现状态保持即可
            # 提示：在实现QQ登录时，真正登录到美多商城的不是QQ用户，而是QQ用户绑定的美多商城用户
            # login(request=request, user='跟openid绑定的美多商城的用户对象')
            login(request=request, user=oauth_qq.user)

            response = http.JsonResponse({'code': 0, 'errmsg': 'OK'})
            response.set_cookie('username', oauth_qq.user.username, max_age=3600 * 24 * 14)
            return response

    def post(self, request):
        """实现openid绑定用户的逻辑"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        sms_code_client = json_dict.get('sms_code')
        access_token = json_dict.get('access_token')

        # 校验参数
        if not all([mobile, password, sms_code_client, access_token]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': '参数password有误'})

        print('test')
        # 校验短信验证码
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)  # sms_code_server是bytes
        # 判断短信验证码是否过期
        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        # 对比用户输入的和服务端存储的短信验证码是否一致
        if sms_code_client != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})
        # 校验openid
        openid = check_access_token_openid(access_token)
        if not openid:
            return http.JsonResponse({'code': 400, 'errmsg': '参数openid有误'})

        # 判断手机号是否存在
        try:
            user = User.objects.get(mobile=mobile)


        except User.DoesNotExist:
            # 手机号码不存在则新建一个用户给美多
            user = User.objects.create_user(username=mobile, password=password, mobile=mobile)

        else:
            if not user.check_password(password):
                return http.JsonResponse({'code': 400, 'errmsg': '密码有误'})

        try:
            OAuthQQUser.objects.create(user=user, openid=openid)

        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': 'qq登录错误'})

        login(request=request, user=user)
        response = http.JsonResponse({'code': 0, 'errmsg': 'OK'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        return response
